package dao;

import db.DatabaseManager;
import model.User;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    public User findByUsername(String username) {
        String sql = "SELECT * FROM users WHERE username = ? AND active = true";
        User user = null;

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                user = new User(
                        rs.getString("username"),
                        rs.getString("password"),
                        rs.getString("role"),
                        rs.getString("real_name")
                );
                user.setPhone(rs.getString("phone"));
                user.setEmail(rs.getString("email"));
                user.setActive(rs.getBoolean("active"));
            }
        } catch (SQLException e) {
            System.out.println("查询用户失败: " + e.getMessage());
        }
        return user;
    }

    public boolean validatePassword(String username, String password) {
        String sql = "SELECT password FROM users WHERE username = ? AND active = true";

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                String storedPassword = rs.getString("password");
                return storedPassword.equals(password);
            }
        } catch (SQLException e) {
            System.out.println("验证密码失败: " + e.getMessage());
        }
        return false;
    }

    public List<User> getAllUsers() {
        List<User> users = new ArrayList<>();
        String sql = "SELECT * FROM users ORDER BY username";

        try (Connection conn = DatabaseManager.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                User user = new User(
                        rs.getString("username"),
                        rs.getString("password"),
                        rs.getString("role"),
                        rs.getString("real_name")
                );
                user.setPhone(rs.getString("phone"));
                user.setEmail(rs.getString("email"));
                user.setActive(rs.getBoolean("active"));
                users.add(user);
            }
        } catch (SQLException e) {
            System.out.println("查询所有用户失败: " + e.getMessage());
        }
        return users;
    }

    public void addUser(User user) {
        String sql = "INSERT INTO users (username, password, role, real_name, phone, email, active) VALUES (?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getRole());
            pstmt.setString(4, user.getRealName());
            pstmt.setString(5, user.getPhone());
            pstmt.setString(6, user.getEmail());
            pstmt.setBoolean(7, user.isActive());
            pstmt.executeUpdate();

        } catch (SQLException e) {
            System.out.println("添加用户失败: " + e.getMessage());
        }
    }

    public void updateUser(User user) {
        String sql = "UPDATE users SET real_name = ?, phone = ?, email = ?, role = ?, active = ? WHERE username = ?";

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, user.getRealName());
            pstmt.setString(2, user.getPhone());
            pstmt.setString(3, user.getEmail());
            pstmt.setString(4, user.getRole());
            pstmt.setBoolean(5, user.isActive());
            pstmt.setString(6, user.getUsername());
            pstmt.executeUpdate();

        } catch (SQLException e) {
            System.out.println("更新用户失败: " + e.getMessage());
        }
    }

    public void changePassword(String username, String newPassword) {
        String sql = "UPDATE users SET password = ? WHERE username = ?";

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, newPassword);
            pstmt.setString(2, username);
            pstmt.executeUpdate();

        } catch (SQLException e) {
            System.out.println("修改密码失败: " + e.getMessage());
        }
    }
}